package com.demo.controller;

import com.demo.config.AppProperties;
import com.demo.model.Auth;
import com.demo.model.LoginDto;
import com.demo.model.UserDto;
import com.demo.service.impl.UserServiceImp;
import com.demo.util.JwtUtil;
import lombok.AllArgsConstructor;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.security.auth.login.AccountNotFoundException;

@AllArgsConstructor
@RestController
@RequestMapping("/authorize")
public class AuthorizeController {

    private final UserServiceImp userServiceImp;
    private final JwtUtil jwtUtil;
    private final AppProperties appProperties;



    @PostMapping("/login")
    public Auth login(@RequestBody LoginDto loginDto) {
        return userServiceImp.login(loginDto.getUsername(),loginDto.getPassword());
    }


    @PostMapping("/refreshToken")
    public Auth refreshToken(@RequestHeader(name = "Authorization") String authorization,@RequestParam String refreshToken){
        authorization = authorization.replace(appProperties.getJwt().getPrefix(),"");
       if( jwtUtil.validateRefreshToken(refreshToken) && jwtUtil.validateWithoutExpiration(authorization)){
           String newToken = jwtUtil.buildAccessTokenWithRefreshToken(refreshToken);
           return new Auth(newToken,refreshToken);
       }else{
            throw new AccessDeniedException("刷新失败");
       }
    }


}
